<template>
  <div class="bone-density-container">
    <el-row :gutter="20">
      <!-- 左侧PDF预览区域 -->
      <el-col :span="12">
        <div class="pdf-viewer-container">
          <div class="pdf-controls">
            <el-button-group>
              <el-button size="small" type="primary" @click="prevFile" :disabled="currentFileIndex === 0">
                上一个文件
              </el-button>
              <el-button size="small" type="success" @click="nextFile" :disabled="currentFileIndex === pdfFiles.length - 1">
                下一个文件
              </el-button>
            </el-button-group>

            <!-- 添加删除按钮（带确认对话框） -->
            <!--            <el-button-->
            <!--              size="small"-->
            <!--              type="danger"-->
            <!--              @click="deleteFile"-->
            <!--              :disabled="!pdfFiles.length"-->
            <!--              v-if="pdfFiles.length">-->
            <!--              删除当前文件-->
            <!--            </el-button>-->

            <el-button size="small" type="primary" @click="triggerFileUpload" class="upload-btn">
              上传PDF文件
            </el-button>
            <input type="file" ref="fileInput" @change="handleFileUpload" multiple accept=".pdf" style="display: none">
          </div>

          <div class="pdf-viewer-wrapper">
            <pdf v-for="page in numPages" :key="page" :src="pdfUrl" :page="page" class="pdf-page">
            </pdf>

            <div class="page-controls">
              <el-button size="mini" @click="prevPage" :disabled="currentPage === 1">
                上一页
              </el-button>
              <span>第 {{ currentPage }} 页 / 共 {{ numPages }} 页</span>
              <el-button size="mini" @click="nextPage" :disabled="currentPage === numPages">
                下一页
              </el-button>
            </div>
          </div>
        </div>
      </el-col>


      <!-- 右侧表单区域 -->
      <el-col :span="12">
        <div class="report-form-container">
          <h1 class="form-title">骨密度数据报告</h1>
          <div slot="footer" class="dialog-footer" style="text-align: right">
            <el-button type="primary" @click="runStrategy" >执行策略</el-button>
            <el-button type="primary" @click="refreshPage" >刷新页面</el-button>
            <el-button type="primary" @click="goToBmdStrategy" >跳转到骨密度策略报告</el-button>
          </div>

          <el-form
            ref="reportForm"
            :model="reportData"
            label-width="100px"
            class="report-form">

            <el-form-item label="基本信息" class="section-title"></el-form-item>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="姓名">
                  <el-input v-model="reportData.name" readonly></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="年龄">
                  <el-input v-model="reportData.age" readonly></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="性别">
                  <el-input v-model="reportData.gender" readonly></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="床号">
                  <el-input v-model="reportData.bedNumber" readonly></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="门诊/住院号">
                  <el-input v-model="reportData.patientNumber" readonly></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="申请科室">
                  <el-input v-model="reportData.department" readonly></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="检查医生">
                  <el-input v-model="reportData.doctor" readonly></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="检查时间">
                  <el-input v-model="reportData.examTime" readonly></el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="检查所见" class="section-title"></el-form-item>
            <el-form-item>
              <el-input
                type="textarea"
                :rows="4"
                v-model="reportData.findings"
                readonly>
              </el-input>
            </el-form-item>

            <el-form-item label="报告结论" class="section-title"></el-form-item>
            <el-form-item>
              <el-input
                type="textarea"
                :rows="4"
                v-model="reportData.conclusion"
                readonly>
              </el-input>
            </el-form-item>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="审核医生">
                  <el-input v-model="reportData.reviewDoctor" readonly></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发布时间">
                  <el-input v-model="reportData.publishTime" readonly></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import pdf from 'vue-pdf'
import {selectPdfUrlList, uploadFiles, deletePdfUrl, selectFileData,runStrategyReport} from "@/api/analysis/report";
export default {
  props: {
    strategyId: {
      type: Number,
      required: true
    }
  },
  components: {
    pdf
  },
  data() {
    return {
      loading: false, // 加载状态
      pdfFiles: [], // 存储上传的PDF文件
      currentFileIndex: -1, // 当前显示的PDF文件索引
      pdfUrl: '', // 当前显示的PDF文件URL
      numPages: 0, // 当前PDF的总页数
      currentPage: 1, // 当前显示的PDF页码

      // 报告数据
      reportData: {
        name: '',
        age: '',
        gender: '',
        bedNumber: '',
        patientNumber: '',
        department: '',
        doctor: '',
        examTime: '',
        findings: '',
        conclusion: '',
        reviewDoctor: '',
        publishTime: ''
      },
      fileListLoading: false,//新增文件列表加载状态
    }
  },
  created() {
    this.fetchPdfFiles()
    this.fetchReportData()
  },
  methods: {
    // 刷新页面
    refreshPage() {
      this.fetchPdfFiles()
      this.fetchReportData()
    },
    //跳转到骨密度策略报告页面
    goToBmdStrategy() {
      let routePath = '';
      routePath = '/bmd/bmdStrategy';
      const {brandId, checkId,reportId} = this.$route.query;
      this.$router.push({
        path: routePath,
        query: {brandId, checkId,reportId}
      });
    },
    // 触发文件上传
    triggerFileUpload() {
      this.$refs.fileInput.click()
    },
    // 优化后的文件上传处理
    handleFileUpload(event) {
      const files = Array.from(event.target.files);
      if (files.length === 0) return;
      // 过滤非PDF文件
      const pdfFiles = files.filter(file => file.type === 'application/pdf');
      if (pdfFiles.length === 0) {
        this.$message.error('请上传PDF文件');
        return;
      }
      // 添加到PDF文件列表
      this.pdfFiles = [...this.pdfFiles, ...pdfFiles]
      // 如果是第一个文件，直接显示
      if (this.currentFileIndex === -1 && this.pdfFiles.length > 0) {
        this.currentFileIndex = 0
        this.loadPdfFile(this.pdfFiles[0])
      }
      // 获取路由参数
      const {brandId, checkId, reportId} = this.$route.query;
      // 准备FormData
      const formData = new FormData();
      // 添加文件
      pdfFiles.forEach(file => {
        formData.append('files', file);
      });
      // 添加其他参数
      if (brandId) formData.append('brandId', brandId);
      if (reportId) formData.append('reportId', reportId);
      if (checkId) formData.append('checkId', checkId);
      // 显示加载状态
      this.loading = true;
      // 调用后端接口
      uploadFiles(pdfFiles, brandId, reportId, checkId).then(response => {
        if (response.code === 200) {
          this.$message.success(`成功上传${pdfFiles.length}个PDF文件`);
          this.fetchPdfFiles(); // 更新文件列表
        } else {
          this.$message.error(response.msg || '文件上传失败');
        }
      }).catch(error => {
        this.$message.error('上传过程中发生错误');
        console.error('上传错误:', error);
      }).finally(() => {
        this.loading = false;
      })
    },


// 修改fetchPdfFiles方法， 从数据库中获取PDF文件列表
    fetchPdfFiles() {
      const {reportId} = this.$route.query;
      this.fileListLoading = true;
      selectPdfUrlList(reportId).then(response => {
        if (response.code === 200 && response.data) {
          this.pdfFiles = response.data;
          // 自动选择最新上传的文件
          const latestFile = this.pdfFiles.find(file => file.isLatest) || this.pdfFiles[0];
          if (latestFile) {
            this.currentFileIndex = this.pdfFiles.indexOf(latestFile);
            this.loadPdfFile(latestFile);
          }
        } else {
          this.$message.error(response.msg || '文件获取失败');
        }
      }).catch(error => {
        console.error("获取文件列表出错：", error);
        this.$message.error("获取文件列表出错");
      }).finally(() => {
        this.fileListLoading = false;
      })
    },
    // 删除PDF文件
    // 添加删除方法
    deleteFile() {
      this.$confirm('确定要删除这个文件吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return deletePdfUrl(39).then(response => {
          if (response.code === 200) {
            this.$message.success('文件删除成功');
            this.fetchPdfFiles(); // 刷新文件列表
          } else {
            this.$message.error(response.msg || '文件删除失败');
          }
        })
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 重置PDF查看器状态
    resetPdfViewer() {
      this.currentFileIndex = -1;
      this.pdfUrl = '';
      this.numPages = 0;
      this.currentPage = 1;
    },

    // 修改loadPdfFile方法
    loadPdfFile(file) {
      if (!file || !file.fileUrl) return;

      this.loading = true;
      // 如果是URL直接使用
      if (file.fileUrl.startsWith('http')) {
        this.pdfUrl = file.fileUrl;
      }
      // 如果是本地文件
      else if (file instanceof File) {
        const fileReader = new FileReader();
        fileReader.onload = () => {
          this.pdfUrl = fileReader.result;
          this.getPdfPageCount();
        };
        fileReader.readAsDataURL(file);
        return;
      }

      this.getPdfPageCount();
    },

    getPdfPageCount() {
      const loadingTask = pdf.createLoadingTask(this.pdfUrl);
      loadingTask.promise.then(pdf => {
        this.numPages = pdf.numPages;
        this.currentPage = 1;
      }).catch(err => {
        console.error('PDF加载错误:', err);
        this.$message.error('PDF文件加载失败');
      }).finally(() => {
        this.loading = false;
      });
    },
    // 上一个PDF文件
    prevFile() {
      if (this.currentFileIndex > 0) {
        this.currentFileIndex--
        this.loadPdfFile(this.pdfFiles[this.currentFileIndex])
      }
    },

    // 下一个PDF文件
    nextFile() {
      if (this.currentFileIndex < this.pdfFiles.length - 1) {
        this.currentFileIndex++
        this.loadPdfFile(this.pdfFiles[this.currentFileIndex])
      }
    },
    // 上一页
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--
      }
    },
    // 下一页
    nextPage() {
      if (this.currentPage < this.numPages) {
        this.currentPage++
      }
    },
    // 从后端获取报告数据
    fetchReportData() {
      try {
        const {reportId} = this.$route.query;
        // 这里替换为实际的API调用
        selectFileData(reportId,fileId).then(response => {
          if (response.code === 200 && response.data) {
            this.reportData = response.data;
          }else {
            this.$message.error(response.msg || '数据解析出错');
          }
        })
      } catch (error) {
        console.error('获取报告数据失败:', error)
        this.$message.error('获取报告数据失败')
      }
    },
    // 执行策略
    runStrategy(){
      try {
        const {brandId, checkId, reportId} = this.$route.query;
        // 这里替换为实际的API调用
        runStrategyReport(brandId, checkId, reportId).then(response => {
          if (response.code === 200 && response.data) {
            this.fetchReportData()
          }else {
            this.$message.error(response.msg || '策略执行出错');
          }
        })
      } catch (error) {
        this.$message.error('获取策略失败')
      }

    },

    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return ''

      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')

      return `${year}-${month}-${day}`
    }
  }
}
</script>

<style scoped>
.bone-density-container {
  padding: 20px;
  background-color: #fff;
  height: calc(100vh - 40px);
  overflow-y: auto;
}

.pdf-viewer-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 15px;
  height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;
}

.pdf-controls {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-btn {
  margin-left: 10px;
}

.pdf-viewer-wrapper {
  flex: 1;
  overflow-y: auto;
  position: relative;
}

.pdf-page {
  margin-bottom: 10px;
  border: 1px solid #ddd;
}

.page-controls {
  margin-top: 10px;
  text-align: center;
}

.report-form-container {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  height: calc(100vh - 100px);
  overflow-y: auto;
}

.form-title {
  text-align: center;
  margin-bottom: 20px;
  color: #409EFF;
}

.section-title {
  font-weight: bold;
  margin-top: 10px;
  margin-bottom: 5px;
}

.report-form {
  margin-top: 20px;
}
</style>
